package org.rcy.framework.data.config.mybatis;


import org.rcy.framework.data.dao.ExcludeDaoFilter;
import org.rcy.framework.data.dao.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public class AutoConfiguredMapperScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware, BeanFactoryAware {

    private static Logger logger = LoggerFactory.getLogger(AutoConfiguredMapperScannerRegistrar.class);

    private BeanFactory beanFactory;
    private ResourceLoader resourceLoader;
    private Environment environment;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        logger.info("Scanning mappers annotated with @Mapper");
        MybatisProperties properties = beanFactory.getBean(MybatisProperties.class);

        Map<String, Object> mapperScanAttrs = importingClassMetadata.getAnnotationAttributes(MybatisMapperScan.class.getName());
        boolean lazyInitialization = (Boolean)mapperScanAttrs.get("lazyInitialization");

        MybatisMapperScanner scanner = new MybatisMapperScanner(registry);

        String[] packages = properties.getBasePackages();

        scanner.setEnvironment(environment);
        scanner.setSqlSessionTemplateBeanName("sqlSessionTemplate");
        scanner.setLazyInitialization(lazyInitialization);
        try {
            scanner.setResourceLoader(resourceLoader);
            scanner.setMarkerInterface(Mapper.class);
            //不扫描BaseDao类
            scanner.addExcludeFilter(new ExcludeDaoFilter());

            scanner.registerFilters();
            scanner.doScan(packages);
        } catch (IllegalStateException ex) {
            logger.debug("Automatic mapper scanning error.", ex);
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

}
